package com.gzq.prototype.practice;

import java.io.*;

public class ShallowClone implements Cloneable , Serializable {

    public static void main(String[] args) throws Exception {
        ShallowClone shallowClone = new ShallowClone();
        System.out.println(shallowClone.hashCode());
        System.out.println(shallowClone.deepProperty.hashCode());

        ShallowClone clone = (ShallowClone) shallowClone.clone();
        System.out.println(clone.hashCode());
        System.out.println(clone.deepProperty.hashCode());

        ShallowClone shallowClone1 = clone.deepClone();
        System.out.println(shallowClone1.hashCode());
        System.out.println(shallowClone1.deepProperty.hashCode());

    }

    public int age = 1;

    public DeepProperty deepProperty = new DeepProperty();

    @Override
    public Object clone() throws CloneNotSupportedException {
        ShallowClone clone = (ShallowClone) super.clone();
        DeepProperty dp = (com.gzq.prototype.practice.DeepProperty) clone.deepProperty.clone();
        clone.deepProperty = (dp);
        return clone;
    }

    public ShallowClone deepClone() throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(this);

        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bais);
        ShallowClone o = (ShallowClone) ois.readObject();
        return o;
    }
}
